var mongojs = require('mongojs');
var db = mongojs('emonitor', ['mongodb://xiong:xiong@ds043262.mongolab.com:43262/emonitor', 'averages']);
var averages = {};
averages.execute = function () {

var mapper = function () {
    emit(Math.floor(this.timeline/60000), {unhappy:this.unhappy, happy:this.happy, surprise:this.surprise, num:1});
    
};
 
var reducer = function (name, values){
  var n = {unhappy : 0, happy : 0, surprise : 0, num : 0};
  for ( var i=0; i<values.length; i++ ){
    n.unhappy += values[i].unhappy;
    n.happy += values[i].happy;
    n.surprise += values[i].surprise;
    n.num += values[i].num;
  }
  return n;
};

var finalize = function(who, res){
  res.unhappy = res.unhappy / res.num;
  res.happy = res.happy / res.num;
  res.surprise = res.surprise / res.num;
  return res;
};
db.emotions.mapReduce(
    mapper,
    reducer,  {

        finalize: finalize,
        out: "averages"
    }
);
};
module.exports = averages;